package com.atguigu.tms.mock.task;

import com.atguigu.mock.util.MyDateUtil;
import com.atguigu.mock.util.RandomBox;
import com.atguigu.mock.util.RandomNum;
import com.atguigu.tms.mock.bean.*;
import com.atguigu.tms.mock.config.AppConfig;
import com.atguigu.tms.mock.constant.TmsConstant;
import com.atguigu.tms.mock.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.atguigu.tms.mock.constant.TmsConstant.TASK_TYPE_COLLECT;

@Component
@Slf4j
public class ExpressDeliveryTask {


    @Autowired
    ExpressTaskDeliveryService expressTaskDeliveryService;

    @Autowired
    ExpressCourierService expressCourierService;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    OrderTraceLogService orderTraceLogService;

    @Autowired
    BaseComplexService baseComplexService;

    @Autowired
    EmployeeInfoService employeeInfoService;


    //检查 待接收的派送
     // 从小区获得派送员
     // 评估时间
    public void  startDelivery(Date curDate  ) {

        List<ExpressTaskDelivery> expressTaskDeliveryList = expressTaskDeliveryService.list(new QueryWrapper<ExpressTaskDelivery>().eq("status", TmsConstant.DELIVERY_STATUS_TODO));

        Map<Long, ExpressCourier> complexCourierMap = expressCourierService.getComplexCourierMap(TmsConstant.EXPRESS_TYPE_DELIVERY);
        Map<Long,ExpressCourier>  expressCourierMap=new HashMap<>();
        List<OrderInfo> orderInfoDeliveringList=new ArrayList<>();
        for (ExpressTaskDelivery expressTaskDelivery : expressTaskDeliveryList) {
            Long orderId = expressTaskDelivery.getOrderId();

            OrderInfo orderInfo = orderInfoService.getById(orderId, true);
            Long receiverComplexId = orderInfo.getReceiverComplexId();
            ExpressCourier expressCourier = complexCourierMap.get(receiverComplexId);

            expressTaskDelivery.setStatus(TmsConstant.DELIVERY_STATUS_DELIVERING );
            expressTaskDelivery.setCourierEmpId(expressCourier.getEmpId());
            EmployeeInfo employeeInfo = employeeInfoService.getById(expressCourier.getEmpId(), true);
            expressTaskDelivery.setCourierName(employeeInfo.getRealName());
            expressTaskDelivery.setStartDeliveryTime(curDate);
            expressTaskDelivery.setUpdateTime(curDate);

            Date estimateHandleDateTime = estimateHandleTime(curDate , AppConfig.send_estimate_handle_hour);
            expressTaskDelivery.setEstimatedEndTime(estimateHandleDateTime);

            courierGetTask(expressCourierMap,expressTaskDelivery);

            orderInfo.setStatus(TmsConstant.ORDER_STATUS_DELIVERING);
            orderInfo.setUpdateTime(curDate);
            orderInfoDeliveringList.add(orderInfo);

            //生成记录
            genOrderTraceLogDelivering(  orderInfo,   expressTaskDelivery);
        }
        orderInfoService.saveOrUpdateBatch(orderInfoDeliveringList,1000,true);
        expressTaskDeliveryService.saveOrUpdateBatch(expressTaskDeliveryList,1000,true);


    }


    private void   courierGetTask(Map<Long,ExpressCourier> expressCourierMap,  ExpressTaskDelivery expressTaskDelivery){
        ExpressCourier expressCourier = expressCourierMap.get(expressTaskDelivery.getCourierEmpId());

        if(expressCourier==null){
              expressCourier  = new ExpressCourier();
              expressCourierMap.put(expressTaskDelivery.getCourierEmpId(),expressCourier);
        }
        List<ExpressTaskDelivery> expressTaskDeliveryList = expressCourier.getExpressTaskDeliveryList();
        expressTaskDeliveryList.add(expressTaskDelivery);

    }

    //从以快递员为单位
    // 从小区获得派送员
    // 评估时间
    public void  doDelivery(Date curDate ) {

        List<ExpressTaskDelivery> expressTaskDeliveryList = expressTaskDeliveryService.list(new QueryWrapper<ExpressTaskDelivery>().eq("status", TmsConstant.DELIVERY_STATUS_DELIVERING));
        log.warn("待派件 : 共 {} 件",expressTaskDeliveryList.size() );
        Map<Long,ExpressCourier>  expressCourierMap=new HashMap<>();

        Map<Long,Long> courierOnComplexMap=new HashMap<>();
  //      Set<Long>  deliveredCourierSet=new HashSet<>();
        List<OrderInfo> orderInfoDeliveringList=new ArrayList<>();
        List<ExpressTaskDelivery> expressTaskDeliveredList= new ArrayList<>();
        for (ExpressTaskDelivery expressTaskDelivery : expressTaskDeliveryList) {
            Long orderId = expressTaskDelivery.getOrderId();
            OrderInfo orderInfo = orderInfoService.getById(orderId, true);
            Long receiverComplexId = orderInfo.getReceiverComplexId();

            Long rightOnComplexId = courierOnComplexMap.get(expressTaskDelivery.getCourierEmpId());
            //该快递员已经开始在小区中 ，而该任务不是此小区的则跳过
            if( rightOnComplexId!=null&&!rightOnComplexId.equals(receiverComplexId)){
               break;
            }


            expressTaskDelivery.setStatus(TmsConstant.DELIVERY_STATUS_DELIVERED );
            expressTaskDelivery.setUpdateTime(curDate);
            expressTaskDelivery.setDeliveredTime(curDate);

            expressTaskDeliveredList.add(expressTaskDelivery);

            courierOnComplexMap.put(expressTaskDelivery.getCourierEmpId(),receiverComplexId);

            orderInfo.setStatus(TmsConstant.ORDER_STATUS_DELIVERED);
            orderInfo.setUpdateTime(curDate);
            orderInfoDeliveringList.add(orderInfo);

            genOrderTraceLogDelivered(  orderInfo,   expressTaskDelivery);
        }
        orderInfoService.saveOrUpdateBatch(orderInfoDeliveringList,1000,true);
        expressTaskDeliveryService.saveOrUpdateBatch(expressTaskDeliveredList,1000,true);

    }

    public void genOrderTraceLogDelivering(OrderInfo orderInfo, ExpressTaskDelivery expressTaskDelivery){
        OrderTraceLog orderTraceLog = new OrderTraceLog();
        orderTraceLog.setOrderId(orderInfo.getId());

        String courierName = expressTaskDelivery.getCourierName();
        ExpressCourier expressCourier = expressCourierService.getById(expressTaskDelivery.getCourierEmpId(), true);

        orderTraceLog.setTraceDesc("快件已交给 "+courierName+", 正在派件中(派单员电话:"+expressCourier.getWorkingPhone()+")");
        orderTraceLog.setCreateTime(expressTaskDelivery.getUpdateTime());
        orderTraceLog.setCurTaskId(expressTaskDelivery.getId());
        orderTraceLog.setChargeEmpId(expressTaskDelivery.getCourierEmpId());
        orderTraceLog.setTaskType(TASK_TYPE_COLLECT);
        orderTraceLog.setIsDeleted("0");
        orderTraceLogService.saveOrUpdate(orderTraceLog );
    }


    public void genOrderTraceLogDelivered(OrderInfo orderInfo, ExpressTaskDelivery expressTaskDelivery){
        OrderTraceLog orderTraceLog = new OrderTraceLog();
        orderTraceLog.setOrderId(orderInfo.getId());

        String courierName = expressTaskDelivery.getCourierName();
        ExpressCourier expressCourier = expressCourierService.getById(expressTaskDelivery.getCourierEmpId(), true);
        Long receiverComplexId = orderInfo.getReceiverComplexId();
        BaseComplex baseComplex = baseComplexService.getById(receiverComplexId);

        orderTraceLog.setTraceDesc("快件已送达"+baseComplex.getComplexName()+"快递站，(如有问题请联系快递员:"+courierName+"，电话:"+expressCourier.getWorkingPhone()+")");
        orderTraceLog.setCreateTime(expressTaskDelivery.getUpdateTime());
        orderTraceLog.setCurTaskId(expressTaskDelivery.getId());
        orderTraceLog.setChargeEmpId(expressTaskDelivery.getCourierEmpId());
        orderTraceLog.setTaskType(TASK_TYPE_COLLECT);
        orderTraceLog.setIsDeleted("0");
        orderTraceLogService.saveOrUpdate(orderTraceLog );
    }



//    private  void  courierDelivery(Date curDate,ExpressCourier expressCourier ){
//        List<ExpressTaskDelivery> expressTaskDeliveryList = expressCourier.getExpressTaskDeliveryList();
//        List<OrderInfo> orderInfoDeliveredList=new ArrayList<>();
//
//        RandomBox ifCanFinishBox = new RandomBox(85, 15);
//        ExpressTaskDelivery expressTaskDelivery  = expressTaskDeliveryList.get(0);
//
//        if(ifCanFinishBox.getRandBoolValue()){
//            expressTaskDelivery.setDeliveryStatus(TmsConstant.DELIVERY_STATUS_DELIVERED);
//            expressTaskDelivery.setUpdateTime(curDate);
//            expressTaskDelivery.setDeliveriedTime(curDate);
//
//            Long orderId = expressTaskDelivery.getOrderId();
//            OrderInfo orderInfo = orderInfoService.getById(orderId, true);
//            orderInfo.setUpdateTime(curDate);
//            orderInfo.setStatus(TmsConstant.ORDER_STATUS_DELIVERED);
//
//            orderInfoDeliveredList.add(orderInfo);
//            orderInfoService.saveOrUpdateBatch(orderInfoDeliveredList,1000,true);
//            expressTaskDeliveryService.saveOrUpdateBatch(expressTaskDeliveryList,1000,true);
//
//        }
//
//    }


    //估计揽收时间
    private Date estimateHandleTime(Date curDate ,Integer handleTime){

        Date finishedDate = DateUtils.addHours(curDate, handleTime);

        int finishHour = MyDateUtil.getHour(finishedDate);

        if(finishHour>=19 || finishHour<=9){  //非工作时间顺延
            handleTime+=14;
        }
        finishedDate = DateUtils.addHours(curDate, handleTime);
        return finishedDate;

    }

 }

